package cn.itlight.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class CustomGateway implements GatewayFilter, Ordered {


    /*
    * @Title: filter
    * @Description: 记录执行的时间
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/31 16:11
    * @Parameters:
    * @Return
    */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //开始时间
        exchange.getAttributes().put("COUNT_Start_TIME", System.currentTimeMillis());
        //执行完成之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    //开始时间
                    Long startTime = exchange.getAttribute("COUNT_Start_TIME");
                    //结束时间
                    Long endTime=(System.currentTimeMillis() - startTime);
                    if (startTime != null) {
                        log.info("111111111111111111");
                        log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                    }
                })
        );
    }

    /*
    * @Title: getOrder
    * @Description: 返回一个int，排序，数字越小，优先级越高
    * @Author: TomLiu
    * @Version: 1.0
    * @Date:  2022/7/31 16:07
    * @Parameters:
    * @Return
    */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
